package com.elvish.oda.busin.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.elvish.oda.busin.pojo.User;

/**
 * 
 * @author Elvish 2017年11月10日
 */
@Controller
public class IndexController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 跳转登录页
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping(value = { "", "/login" })
	public String preLogin(HttpServletRequest request) {
		return "/login";
	}

	/**
	 * 用户登录
	 * 
	 * @param user
	 *            登录form数据
	 * @param map
	 *            modelmap
	 * @return true：初始化菜单；false：返回登录页
	 */
	@PostMapping(value = "/sys/login")
	public String login(User user, ModelMap map) {
		String msg = "";
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
		try {
			subject.login(token);
			return "redirect:/sys/initMenu";
		} catch (UnknownAccountException e) {
			msg = e.getMessage();
		} catch (LockedAccountException e) {
			msg = e.getMessage();
		} catch (IncorrectCredentialsException e) {
			msg = e.getMessage();
		}
		map.put("msg", msg);
		return "/login";
	}

	/**
	 * 用户退出
	 * 
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/sys/logout")
	public String logout(HttpServletRequest request) {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "/login";
	}
}
